import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_ns_ble/flutter_ns_ble.dart';
import 'package:flutter_ns_ble_example/main_page.dart';
import 'package:permission_handler/permission_handler.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    Peripheral.logEvent.listen((event){
      print("AppState:${event.priority}, ${event.message}");
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: IndexPage());
  }
}

class IndexPage extends StatelessWidget {
  const IndexPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Plugin example app'),
        actions: [
          StreamBuilder(
            stream: FlutterBluePlus.isScanning,
            builder: (context, snapshot) {
              if (snapshot.data == true) {
                return TextButton(
                  onPressed: () async {
                    await Permission.bluetoothScan.request();
                    await Permission.bluetoothConnect.request();
                    FlutterBluePlus.stopScan();
                  },
                  child: Text('StopScan'),
                );
              } else {
                return TextButton(
                  onPressed: () async {
                    await Permission.bluetoothScan.request();
                    await Permission.bluetoothConnect.request();
                    FlutterBluePlus.startScan(
                      withKeywords: ['KY'],
                      timeout: Duration(seconds: 30),
                    );
                  },
                  child: Text('Scan'),
                );
              }
            },
          ),
          TextButton(onPressed: () async {}, child: Text('Main')),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: StreamBuilder(
              stream: FlutterBluePlus.scanResults,
              builder: (context, snapshot) {
                if (snapshot.hasError) {
                  print(snapshot.error);
                  return Text("snapshot.error:${snapshot.error}");
                }
                var connectedDevices = FlutterBluePlus.connectedDevices;
                return CustomScrollView(
                  slivers: [
                    SliverList.builder(
                      itemBuilder: (context, index) {
                        var model = connectedDevices[index];
                        return ListTile(
                          title: Text(model.platformName ?? ''),
                          subtitle: Text(model.remoteId.str),
                          onTap: () async {
                            Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (context) {
                                  return MainPage(
                                    peripheral: Peripheral(
                                      name: model.platformName,
                                      address: model.remoteId.str,
                                    ),
                                  );
                                },
                              ),
                            );
                          },
                        );
                      },
                      itemCount: connectedDevices.length,
                    ),
                    SliverList.builder(
                      itemBuilder: (context, index) {
                        var model = snapshot.data![index];
                        return ListTile(
                          title: Text(model.device.platformName ?? ''),
                          subtitle: Text(model.device.remoteId.str),
                          onTap: () async {
                            Navigator.of(context).push(
                              MaterialPageRoute(
                                builder: (context) {
                                  return MainPage(
                                    peripheral: Peripheral(
                                      name: model.device.platformName,
                                      address: model.device.remoteId.str,
                                    ),
                                  );
                                },
                              ),
                            );
                          },
                        );
                      },
                      itemCount: snapshot.data?.length ?? 0,
                    ),
                  ],
                );
              },
            ),
          ),
          StreamBuilder(
            stream: FlutterBluePlus.adapterState,
            builder: (context, snapshot) {
              return Text("Central Manager State: ${snapshot.data?.name}");
            },
          ),
        ],
      ),
    );
  }
}
